<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/super/favicon.ico" />
    <title>科普文章列表 - 见闻间管理后台</title>
    <!-- <script type="module" crossorigin src="/super/assets/index-abba05ce.js"></script> -->
    <link rel="stylesheet" href="/super/assets/index-a23242ca.css">
    <style>
        /* 基础页面样式 */
        body {
            background-color: #121212;
            color: #ffffff;
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
        }

        .app-loading {
            position: absolute;
            top: 0px;
            left: 0px;
            right: 0px;
            bottom: 0px;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            background: #212121;
        }

        .app-loading__loader {
            position: relative;
        }

        .loading__logo {
            position: absolute;
            z-index: 1;
            inset: 10px;
            width: 44px;
            height: 44px;
            border-radius: 50%;
        }

        .loading__loader {
            width: 64px;
            height: 64px;
            border-radius: 50%;
            border: 3px solid rgba(255, 255, 255, 0.1);
            border-left-color: #4CAF50;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        .science-container {
            padding: 20px;
            max-width: 100%;
            width: 100%;
        }

        .science-container h1 {
            color: #ffffff;
            margin-bottom: 20px;
        }
        
        /* 按钮样式 */
        .action-buttons {
            margin-bottom: 20px;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .btn-primary {
            background-color: #4CAF50;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #45a049;
        }
        
        .btn-small {
            padding: 5px 10px;
            font-size: 12px;
        }
        
        .btn-edit {
            background-color: #2196F3;
            color: white;
        }
        
        .btn-edit:hover {
            background-color: #0b7dda;
        }

        /* 搜索区域样式 */
        .search-area {
            background-color: #1e1e1e;
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .search-item {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .search-item label {
            color: #cccccc;
            font-size: 14px;
        }

        .search-input {
            padding: 8px 12px;
            background-color: #2d2d2d;
            border: 1px solid #444;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            min-width: 200px;
        }

        .search-input:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .search-select {
            padding: 8px 12px;
            background-color: #2d2d2d;
            border: 1px solid #444;
            border-radius: 4px;
            color: #ffffff;
            font-size: 14px;
            min-width: 120px;
        }

        .search-select:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .search-btn {
            padding: 9px 20px;
            background-color: #4CAF50;
            border: none;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
            align-self: flex-end;
        }

        .search-btn:hover {
            background-color: #45a049;
        }

        /* 表格样式 */
        .science-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: #1e1e1e;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
            border-radius: 8px;
            overflow: hidden;
        }

        .science-table th,
        .science-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #333;
            color: #ffffff;
        }

        .science-table th {
            background-color: #2d2d2d;
            font-weight: bold;
            color: #ffffff;
        }

        .science-table tr:hover {
            background-color: #2a2a2a;
        }

        .science-table tr:nth-child(even) {
            background-color: #222222;
        }

        .science-table .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }

        .science-table .status-published {
            background-color: #1b5e20;
            color: #a5d6a7;
        }

        .science-table .status-draft {
            background-color: #e65100;
            color: #ffe0b2;
        }

        /* 分页样式 */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 30px;
            gap: 10px;
        }

        .pagination-btn {
            padding: 8px 12px;
            border: 1px solid #444;
            background-color: #2d2d2d;
            color: #ffffff;
            cursor: pointer;
            border-radius: 4px;
            transition: all 0.3s;
        }

        .pagination-btn:hover:not(:disabled) {
            background-color: #3d3d3d;
            border-color: #4CAF50;
        }

        .pagination-btn.active {
            background-color: #4CAF50;
            color: #fff;
            border-color: #4CAF50;
        }

        .pagination-btn:disabled {
            cursor: not-allowed;
            opacity: 0.5;
            background-color: #1e1e1e;
            border-color: #333;
        }

        .pagination-info {
            margin: 0 10px;
            color: #cccccc;
        }
    </style>
</head>

<body>
    <div id="app">
        <div class="app-loading" id="loading">
            <div class="app-loading__loader">
                <img class="loading__logo" src="/super/assets/logo-ef86275c.png" />
                <div class="loading__loader"></div>
            </div>
        </div>
        
        <div class="science-container" style="display: none;">
            <h1>科普文章列表</h1>
            
            <!-- 操作按钮区域 -->
            <div class="action-buttons">
                <button id="add-article-btn" class="btn btn-primary" onclick="console.log('添加文章按钮被点击'); window.location.href='/science/edit/index'">添加文章</button>
            </div>
            
            <!-- 搜索区域 -->
            <div class="search-area">
                <div class="search-item">
                    <label for="search-title">标题</label>
                    <input type="text" id="search-title" class="search-input" placeholder="请输入文章标题">
                </div>
                
                <div class="search-item">
                    <label for="search-category">分类</label>
                    <select id="search-category" class="search-select">
                        <option value="">全部分类</option>
                        <!-- 分类选项将通过JavaScript动态添加 -->
                    </select>
                </div>
                
                <div class="search-item">
                    <label for="search-status">状态</label>
                    <select id="search-status" class="search-select">
                        <option value="">全部状态</option>
                        <option value="1">已发布</option>
                        <option value="0">未发布</option>
                    </select>
                </div>
                
                <button id="search-btn" class="search-btn">查询</button>
            </div>
            
            <table class="science-table" id="science-list">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>标题</th>
                        <th>分类</th>
                        <th>发布时间</th>
                        <th>状态</th>
                        <th>浏览量</th>
                        <th>点赞数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <!-- 分页控件 -->
            <div id="pagination" class="pagination"></div>
        </div>
    </div>

    <script>
        // 显示加载中
        function showLoading() {
            const loadingElement = document.getElementById('loading');
            const containerElement = document.querySelector('.science-container');
            
            if (loadingElement) {
                loadingElement.style.display = 'flex';
            }
            
            if (containerElement) {
                containerElement.style.display = 'none';
            }
        }

        // 隐藏加载中
        function hideLoading() {
            const loadingElement = document.getElementById('loading');
            const containerElement = document.querySelector('.science-container');
            
            if (loadingElement) {
                loadingElement.style.display = 'none';
            }
            
            if (containerElement) {
                containerElement.style.display = 'block';
            }
        }

        // 全局分页状态
        let currentPage = 1;
        let totalCount = 0;
        let pageSize = 10;
        let totalPages = 0;

        // 获取分类数据
        async function fetchCategories() {
            try {
                const url = new URL('/science/api/categories', window.location.origin);
                const response = await fetch(url);
                const data = await response.json();
                
                if ((data.code === 200 || data.code === 0) && data.data) {
                    // 渲染分类下拉框
                    const categorySelect = document.getElementById('search-category');
                    if (categorySelect) {
                        // 清空现有选项（保留"全部分类"）
                        while (categorySelect.options.length > 1) {
                            categorySelect.remove(1);
                        }
                        
                        // 添加分类选项
                        data.data.forEach(category => {
                            const option = document.createElement('option');
                            option.value = category.id;
                            option.textContent = category.name;
                            categorySelect.appendChild(option);
                        });
                    }
                }
            } catch (error) {
                console.error('获取分类列表失败:', error);
                // 如果API调用失败，使用备用分类数据
                const categories = [
                    { id: 1, name: '热点' },
                    { id: 2, name: '专家科普' },
                    { id: 3, name: '生活' },
                    { id: 4, name: '睡眠' },
                    { id: 5, name: '辟谣' },
                    { id: 6, name: '行业频' }
                ];
                
                const categorySelect = document.getElementById('search-category');
                if (categorySelect) {
                    while (categorySelect.options.length > 1) {
                        categorySelect.remove(1);
                    }
                    
                    categories.forEach(category => {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        categorySelect.appendChild(option);
                    });
                }
            }
        }

        // 获取科普文章列表
        async function fetchScienceList(page = 1) {
            showLoading();
            try {
                // 在API请求中传递页码参数和搜索参数
                const url = new URL('/science/api/list', window.location.origin);
                url.searchParams.append('page', page);
                url.searchParams.append('page_size', pageSize);
                
                // 获取搜索参数
                const title = document.getElementById('search-title')?.value.trim() || '';
                const categoryId = document.getElementById('search-category')?.value || '';
                const status = document.getElementById('search-status')?.value || '';
                
                // 添加搜索参数
                if (title) {
                    url.searchParams.append('title', title);
                }
                if (categoryId) {
                    url.searchParams.append('category_id', categoryId);
                }
                if (status !== '') {
                    url.searchParams.append('status', status);
                }
                
                const response = await fetch(url);
                const data = await response.json();
                
                const scienceListElement = document.getElementById('science-list');
                // 根据success函数定义，成功状态码是200
                if ((data.code === 200 || data.code === 0) && data.data) {
                    // 保存分页数据
                    currentPage = data.data.page || page;
                    totalCount = data.data.total || 0;
                    pageSize = data.data.pageSize || 10;
                    totalPages = Math.ceil(totalCount / pageSize);
                    
                    // 渲染文章列表
                    renderScienceList(data.data.list || []);
                    // 渲染分页控件
                    renderPagination();
                } else if (scienceListElement) {
                    const tbody = scienceListElement.querySelector('tbody');
                    if (tbody) {
                        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无文章数据</td></tr>';
                    }
                    // 清空分页控件
                    const paginationElement = document.getElementById('pagination');
                    if (paginationElement) {
                        paginationElement.innerHTML = '';
                    }
                }
            } catch (error) {
                // console.error('获取文章列表失败:', error);
                const scienceListElement = document.getElementById('science-list');
                if (scienceListElement) {
                    const tbody = scienceListElement.querySelector('tbody');
                    if (tbody) {
                        tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">获取文章列表失败，请重试</td></tr>';
                    }
                }
                // 清空分页控件
                const paginationElement = document.getElementById('pagination');
                if (paginationElement) {
                    paginationElement.innerHTML = '';
                }
            } finally {
                hideLoading();
            }
        }

        // 渲染科普文章列表
        function renderScienceList(articles) {
            const container = document.getElementById('science-list');
            if (!container) return;
            
            const tbody = container.querySelector('tbody');
            if (!tbody) return;
            
            if (articles.length === 0) {
                tbody.innerHTML = '<tr><td colspan="7" style="text-align: center;">暂无文章数据</td></tr>';
                return;
            }

            const html = articles.map(article => `
                <tr>
                    <td>${article.id || '-'}</td>
                    <td>
                        <div style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                            ${article.title || '未命名文章'}
                        </div>
                    </td>
                    <td>${article.category?.name || article.category_name || '未分类'}</td>
                    <td>${article.create_time || article.publish_time || '-'}</td>
                    <td>
                        <span class="status-badge ${article.status === 1 ? 'status-published' : 'status-draft'}">
                            ${article.status === 1 ? '已发布' : '未发布'}
                        </span>
                    </td>
                    <td>${article.user?.views || article.views || 0}</td>
                    <td>${article.likes || 0}</td>
                    <td>
                        <button class="btn btn-small btn-edit" data-id="${article.id}">编辑</button>
                    </td>
                </tr>
            `).join('');

            tbody.innerHTML = html;
        }

        // 渲染分页控件
        function renderPagination() {
            const paginationElement = document.getElementById('pagination');
            if (!paginationElement) return;

            // 清空现有分页控件
            paginationElement.innerHTML = '';

            // 创建首页按钮
            const firstPageBtn = document.createElement('button');
            firstPageBtn.className = 'pagination-btn';
            firstPageBtn.textContent = '首页';
            firstPageBtn.disabled = currentPage === 1;
            firstPageBtn.addEventListener('click', () => fetchScienceList(1));
            paginationElement.appendChild(firstPageBtn);

            // 创建上一页按钮
            const prevPageBtn = document.createElement('button');
            prevPageBtn.className = 'pagination-btn';
            prevPageBtn.textContent = '上一页';
            prevPageBtn.disabled = currentPage === 1;
            prevPageBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    fetchScienceList(currentPage - 1);
                }
            });
            paginationElement.appendChild(prevPageBtn);

            // 创建页码信息
            const pageInfo = document.createElement('span');
            pageInfo.className = 'pagination-info';
            pageInfo.textContent = `${currentPage} / ${totalPages} 页，共 ${totalCount} 条`;
            paginationElement.appendChild(pageInfo);

            // 创建下一页按钮
            const nextPageBtn = document.createElement('button');
            nextPageBtn.className = 'pagination-btn';
            nextPageBtn.textContent = '下一页';
            nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            nextPageBtn.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    fetchScienceList(currentPage + 1);
                }
            });
            paginationElement.appendChild(nextPageBtn);

            // 创建尾页按钮
            const lastPageBtn = document.createElement('button');
            lastPageBtn.className = 'pagination-btn';
            lastPageBtn.textContent = '尾页';
            lastPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            lastPageBtn.addEventListener('click', () => fetchScienceList(totalPages));
            paginationElement.appendChild(lastPageBtn);
        }

        // 页面加载完成后获取数据
        window.addEventListener('DOMContentLoaded', async () => {
            // 先获取分类数据
            await fetchCategories();
            // 然后获取文章列表
            fetchScienceList(1);
            
            // 绑定查询按钮点击事件
            const searchBtn = document.getElementById('search-btn');
            if (searchBtn) {
                searchBtn.addEventListener('click', () => fetchScienceList(1));
            }
            
            // 已在HTML中使用内联onclick属性实现跳转功能
            // 保留下面的代码用于调试
            const addArticleBtn = document.getElementById('add-article-btn');
            if (addArticleBtn) {
                console.log('找到了添加文章按钮，onclick属性已设置');
                // 确保按钮是可见的并且可点击
                console.log('按钮样式状态:', {
                    display: window.getComputedStyle(addArticleBtn).display,
                    visibility: window.getComputedStyle(addArticleBtn).visibility,
                    pointerEvents: window.getComputedStyle(addArticleBtn).pointerEvents
                });
            } else {
                console.error('未找到ID为add-article-btn的按钮');
            }
            
            // 为编辑按钮添加事件委托
            const scienceListElement = document.getElementById('science-list');
            if (scienceListElement) {
                scienceListElement.addEventListener('click', (e) => {
                    if (e.target.classList.contains('btn-edit')) {
                        const articleId = e.target.getAttribute('data-id');
                        window.location.href = new URL(`/science/edit/index?id=${articleId}`, window.location.origin).href;
                    }
                });
            }
        });
    </script>
</body>

</html>